package com.example.shop.fgo.task.upload.controller;

import android.content.Intent;

import com.example.shop.fgo.base.YBaseApp;
import com.example.shop.fgo.entity.FileListEntity;
import com.example.shop.fgo.task.common.controller.TaskController;
import com.example.shop.fgo.task.common.controller.TaskMsg;
import com.example.shop.fgo.task.common.controller.UpdatePart;
import com.example.shop.fgo.task.common.model.TaskState;
import com.example.shop.fgo.task.upload.model.SDEntity;
import com.example.shop.fgo.task.upload.model.UploadDaoConfig;
import com.example.shop.fgo.task.upload.model.UploadTask;
import com.example.shop.fgo.utils.MakeFileHash;

import org.greenrobot.eventbus.EventBus;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.List;

/**
 * Created by Administrator on 2017/2/20.
 */

public class UploadController implements TaskController<UploadTask> {
    private DbManager.DaoConfig mDaoConfig;

    public UploadController() {

        mDaoConfig = UploadDaoConfig.getUploadDaoConfig();
    }

    /**
     * 添加一堆任务到上传队列
     *
     * @param dataEntities 目标任务们
     * @param pathEntities 所处路径PathEntity集合
     */
    public void addTasksToQueue(List<FileListEntity.DataEntity> dataEntities, List<FileListEntity.PathEntity> pathEntities) {



    }


    public void addTasksToQueue(List<SDEntity> sdEntities, String cid) {
        for (SDEntity sdEntity : sdEntities) {
            if (!sdEntity.isDir()) {
                //添加一个文件
                addFileTaskToQueue(sdEntity, cid);
            } else {
                //添加一个文件夹
                addDirTaskToQueue(sdEntity, cid);
            }
        }

        startTasks();
    }

    /**
     * 添加一个文件夹里的全部东西到上传队列中，如果文件夹有子文件夹，那么就继续添加子文件夹里的全部东西到上传队列中，循环往复。。
     *
     * @param sdEntity
     */
    private void addDirTaskToQueue(SDEntity sdEntity, String cid) {


        addTasksToQueue(GetSDEntityUtil.getDir(sdEntity.getAbsolutePath()),cid);

    }

    private void addFileTaskToQueue(SDEntity sdEntity, String cid) {

        UploadTask uploadTask = new UploadTask();

        uploadTask.setName(sdEntity.getName());
        uploadTask.setTotalSize((int) sdEntity.getSize());
        uploadTask.setFilePath(sdEntity.getAbsolutePath());
        uploadTask.setSha1(MakeFileHash.getFileSHA1(sdEntity.getAbsolutePath()));
        uploadTask.setUrl(sdEntity,cid);
        uploadTask.setTime(System.currentTimeMillis());
        uploadTask.setU(null);
        uploadTask.setIco(sdEntity.getIco());
        uploadTask.setState(TaskState.TASK_STATE_WAIT);
        uploadTask.setPid(cid);
        try {
            x.getDb(mDaoConfig).save(uploadTask);
        } catch (DbException e) {
            e.printStackTrace();
        }

    }


    protected void updateUploadTaskState(UploadTask uploadTask, int newState) {
        uploadTask.setState(newState);
        try {
            x.getDb(mDaoConfig).update(uploadTask, "state");
        } catch (DbException e) {
            e.printStackTrace();
        }

        TaskMsg uploadMsg = TaskMsg.obtain();
        uploadMsg.mUpdatePart = UpdatePart.STATE;
        uploadMsg.mTask = uploadTask;
        EventBus.getDefault().post(uploadMsg);
    }

    /**
     * @param uploadTask 哪个任务
     * @param newSize      又上传了多少
     */
    protected void updateUploadTaskSize(UploadTask uploadTask, int newSize) {
        uploadTask.setNowSize(uploadTask.getNowSize() + newSize);
        try {
            x.getDb(mDaoConfig).update(uploadTask, "nowSize", "nowSizeStr");
        } catch (DbException e) {
            e.printStackTrace();
        }
        TaskMsg uploadMsg = TaskMsg.obtain();
        uploadMsg.mUpdatePart = UpdatePart.SIZE;
        uploadMsg.mTask = uploadTask;
        EventBus.getDefault().post(uploadMsg);
    }

    /**
     * @param uploadTask 哪个任务
     * @param newSpeed     新速度
     */
    protected void updateUploadTaskSpeed(UploadTask uploadTask, String newSpeed) {
        uploadTask.setSpeed(newSpeed);
        try {
            x.getDb(mDaoConfig).update(uploadTask, "speed");
        } catch (DbException e) {
            e.printStackTrace();
        }
        TaskMsg uploadMsg = TaskMsg.obtain();
        uploadMsg.mUpdatePart = UpdatePart.SPEED;
        uploadMsg.mTask = uploadTask;
        EventBus.getDefault().post(uploadMsg);
    }


    /**
     * 用于正在执行的上传任务列表
     *
     * @return
     */
    public List<UploadTask> getTasksUnDone() {
        try {
            return x.getDb(mDaoConfig).selector(UploadTask.class).where("state", "<>", TaskState.TASK_STATE_DONE)
                    .and("state", "<>", TaskState.TASK_STATE_CANCEL).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 用于已完成的上传任务列表
     *
     * @return
     *
     */
    public List<UploadTask> getTasksDone() {
        try {
            return x.getDb(mDaoConfig).selector(UploadTask.class).where("state", "==", TaskState.TASK_STATE_DONE)
                    .findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 找到一个处于排队的上传任务，我们把它拿去执行上传动作
     *
     * @return 处于排队的上传任务
     */
    protected UploadTask getUploadTaskWait() {
        try {
            return x.getDb(mDaoConfig).selector(UploadTask.class).where("state", "=", TaskState.TASK_STATE_WAIT).findFirst();
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 开始执行上传
     */
    public void startTasks() {
        Intent intent = new Intent(YBaseApp.mContextGlobal, UploadService.class);
        YBaseApp.mContextGlobal.startService(intent);
    }

    /**
     * 删除指定任务
     *
     * @param uploadTask
     */
    public void cancelTask(UploadTask uploadTask) {



        updateUploadTaskState(uploadTask, TaskState.TASK_STATE_CANCEL);

    }

    /**
     * 暂停指定任务
     *
     * @param uploadTask
     */
    public void pauseTask(UploadTask uploadTask) {


        updateUploadTaskState(uploadTask, TaskState.TASK_STATE_PAUSE);

    }

    /**
     * 暂停指定任务
     *
     * @param uploadTask
     */
    public void resumeTask(UploadTask uploadTask) {

        updateUploadTaskState(uploadTask, TaskState.TASK_STATE_WAIT);
        startTasks();

    }


    /**
     * 判断某个任务是否被删除
     */

    protected boolean hasCanceled(UploadTask uploadTask) {
        try {
            UploadTask task = x.getDb(mDaoConfig).findById(UploadTask.class, uploadTask.getId());

            if (task == null) {
                return true;
            }

            if (task.getState() == TaskState.TASK_STATE_CANCEL) {
                return true;
            }
            return false;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断某个任务是否被暂停
     */

    protected boolean haspaused(UploadTask uploadTask) {
        try {
            UploadTask task = x.getDb(mDaoConfig).findById(UploadTask.class, uploadTask.getId());

            if (task == null) {
                return true;
            }

            if (task.getState() == TaskState.TASK_STATE_PAUSE) {
                return true;
            }
            return false;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }


}
